package com.hmall.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.math.BigInteger;

/**
 * JSON序列化配置类
 * 功能：自定义Jackson ObjectMapper的序列化规则
 * 场景：解决前端JS处理长整型（Long）精度丢失问题
 */
@Configuration
@ConditionalOnClass(ObjectMapper.class) // 仅当类路径中存在ObjectMapper时生效
public class JsonConfig {

    /**
     * 配置Jackson ObjectMapper的序列化规则
     * @return Jackson2ObjectMapperBuilderCustomizer实例
     * 核心逻辑：
     * 1. 将Long类型序列化为字符串（避免JS精度丢失）
     * 2. 将BigInteger类型序列化为字符串（支持大整数传输）
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            // 处理Long类型序列化（转为字符串）
            jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
            // 处理BigInteger类型序列化（转为字符串）
            jacksonObjectMapperBuilder.serializerByType(BigInteger.class, ToStringSerializer.instance);
        };
    }
}